//package com.growthserver.util;
//
//import cn.hutool.core.codec.Base64Decoder;
//import cn.hutool.core.codec.Base64Encoder;
//import cn.hutool.crypto.digest.DigestUtil;
//import cn.hutool.http.HttpRequest;
//import cn.hutool.http.HttpResponse;
//import com.alibaba.fastjson.JSONObject;
//import com.ly.mp.springcloudnacos.nacos.NacosConfigs;
//import ly.mp.project.common.vo.ErrorCode;
//import ly.mp.project.common.vo.ErrorMsg;
//import ly.mp.project.common.vo.ResponseVO;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpStatus;
//import org.apache.http.NameValuePair;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.utils.HttpClientUtils;
//import org.apache.http.client.utils.URIBuilder;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.message.BasicNameValuePair;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import javax.crypto.Cipher;
//import javax.crypto.spec.SecretKeySpec;
//import javax.servlet.http.HttpServletRequest;
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.security.Security;
//import java.util.*;
//
//public class HttpCenterUtils {
//
//    //添加共用httpClient
//    private static CloseableHttpClient httpClient = HttpClients.custom().evictExpiredConnections().setMaxConnTotal(700).setMaxConnPerRoute(100).build();
//    private static final Logger logger = LoggerFactory.getLogger(HttpCenterUtils.class);
//
//    private static String contentTyped = "application/x-www-form-urlencode";
//
//    /**
//     * post 拼接url参数
//     * @param url
//     * @param paramMap
//     * @param acceptLanguage
//     * @return
//     * //List<NameValuePair> list = new LinkedList<>();
//     * //BasicNameValuePair param2 = new BasicNameValuePair("key2", "value2");
//     * //list.add(param1);
//     */
//    public static JSONObject doPostParam(String url, HashMap<String,Object> paramMap, HttpServletRequest servletRequest, String acceptLanguage){
//        String lang = "zh-CN".equals(acceptLanguage) ? "cn":"en";
//        ResponseVO errRes = new ResponseVO();
//        errRes.setResult(ErrorCode.EC2002);
//        errRes.setMsg(ErrorMsg.getErrMsg(ErrorCode.EC2002,lang));
//        //创建 CloseableHttpClient
////        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        String result = null;
//        HttpPost httpPost = null;
//        try {
//            URIBuilder uri = new URIBuilder(url);
//            List<NameValuePair> paramList = new LinkedList<>();
//            if(paramMap != null){
//                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
//                    String key = entry.getKey();
//                    String value = entry.getValue()== null ? null:entry.getValue().toString();
//                    paramList.add(new BasicNameValuePair(key, value));
//                }
//            }
//
//            uri.setParameters(paramList);
//            httpPost = new HttpPost(uri.build());
//            RequestConfig requestConfig = RequestConfig.custom()
//                    .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
//                    .setSocketTimeout(3000).build();
//            httpPost.setConfig(requestConfig);
//            httpPost.setHeader("Accept-Language",acceptLanguage);
//            if(servletRequest!=null){
//                String UA = servletRequest.getHeader("UA");
//                if(StringUtils.isNotBlank(UA)){
//                    httpPost.setHeader("UA",UA);
//                }
//                //添加灰度标识
//                String gversion = servletRequest.getHeader("gversion");
//                if(StringUtils.isNotBlank(gversion)){
//                    httpPost.setHeader("gversion",gversion);
//                }
//                String xRequestId = servletRequest.getHeader("X-Request-ID");
//                if(StringUtils.isNotBlank(xRequestId)){
//                    httpPost.setHeader("X-Request-ID",xRequestId);
//                }
//            }
//            response = httpClient.execute(httpPost);
//            int status = response.getStatusLine().getStatusCode();//获取返回状态值
//            if (status == HttpStatus.SC_OK) {//请求成功
//                HttpEntity httpEntity = response.getEntity();
//                if(httpEntity != null){
//                    result = EntityUtils.toString(httpEntity, "UTF-8");
//                    EntityUtils.consume(httpEntity);//关闭资源
//                    JSONObject jsonResult = JSONObject.parseObject(result);
//                    return jsonResult;
//                }
//            }else{
//                return (JSONObject) JSONObject.toJSON(errRes);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            HttpClientUtils.closeQuietly(response);
//            if(httpPost!=null){
//                httpPost.releaseConnection();
//            }
////            if(response != null){
////                try {
////                    response.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
////            }
////            if(httpClient != null){
////                try {
////                    httpClient.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
////            }
//        }
//        return (JSONObject) JSONObject.toJSON(errRes);
//    }
//
//    /**
//     * post json字符串
//     * @param url
//     * @param json
//     * @param servletRequest
//     * @return
//     */
//    public static JSONObject doPostJson(String url, String json, HttpServletRequest servletRequest) {
//        //创建 CloseableHttpClient
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        // 声明呀一个字符串用来存储response
//        String result = "{\"result\":\"2002\",\"msg\":\"系统繁忙,请稍后再试\"}";
//        // 创建httppost对象
//        HttpPost httpPost = new HttpPost(url);
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
//                .setSocketTimeout(3000).build();
//        httpPost.setConfig(requestConfig);
//        // 给httppost对象设置json格式的参数
//        StringEntity httpEntity = new StringEntity(json,"utf-8");
//        // 设置请求格式
//        httpPost.setHeader("Content-type","application/json");
//        httpPost.setHeader("Accept-Encoding","");
//        if(servletRequest!=null){
//            String UA = servletRequest.getHeader("UA");
//            if(StringUtils.isNotBlank(UA)){
//                httpPost.setHeader("UA",UA);
//            }
//            //添加灰度标识
//            String gversion = servletRequest.getHeader("gversion");
//            if(StringUtils.isNotBlank(gversion)){
//                httpPost.setHeader("gversion",gversion);
//            }
//            String xRequestId = servletRequest.getHeader("X-Request-ID");
//            if(StringUtils.isNotBlank(xRequestId)){
//                httpPost.setHeader("X-Request-ID",xRequestId);
//            }
//        }
//        //设置appid和秘钥
//        setPostHeader(httpPost);
//        // 传参
//        httpPost.setEntity(httpEntity);
//        // 发送请求，并获取返回值
//        try {
//            long start = System.currentTimeMillis();
//            response = httpClient.execute(httpPost);
//            InputStream in = response.getEntity().getContent();
//            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
//            StringBuilder strber= new StringBuilder();
//            String line = null;
//            while((line = br.readLine())!=null){
//                strber.append(line+'\n');
//            }
//            br.close();
//            in.close();
//            result = strber.toString();
//            //返回结果 响应码200
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }finally {
//            HttpClientUtils.closeQuietly(response);
//            httpPost.releaseConnection();
//        }
//        return  JSONObject.parseObject(result);
//    }
//
//    public static void setPostHeader(HttpPost httpPost){
//        httpPost.setHeader("appid", NacosConfigs.getProp("middle.appid"));
//        httpPost.setHeader("securetkey", DigestUtil.md5Hex(NacosConfigs.getProp("middle.securetkey")));
//    }
//
//    public static  boolean isSuccess(JSONObject jsonObject){
//        String result = jsonObject.getString("result");
//        if("1".equals(result)){
//            return true;
//        }
//        return  false;
//    }
//
//
//    /**
//            * AES的加密函数
//	 * @param str 传入需要加密的字符
//	 * @param key 传入一个16位长度的密钥。否则报错
//	 * @return 执行成功返回加密结果，否则报错
//	 * @throws Exception 抛出一个加密异常
//	 */
//    public static String aesEncrypt(String str,String key) throws Exception {
//        Security.setProperty("crypto.policy", "unlimited");
//        if (str == null || key == null) return null;
//        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
//        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
//        return  Base64Encoder.encode(bytes);
//
//    }
//    /**
//     * AES的解密函数
//     * @param str 传入需要解密的字符
//     * @param key 传入一个16位长度的密钥。否则报错
//     * @return 执行成功返回加密结果，否则报错
//     * @throws Exception 抛出一个解密异常
//     */
//    public static String aesDecrypt(String str,String key) throws Exception {
//        if (str == null || key == null) return null;
//        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
//        byte[] bytes = Base64Decoder.decode(str);
//
//        bytes = cipher.doFinal(bytes);
//        return new String(bytes, "utf-8");
//    }
//
//    public static String httpClientTest(String api, String body,String bdpUserKey,String bdpUserSecret,String bdpGwUrl) throws Exception{
//        String noncestr = UUID.randomUUID().toString().replaceAll("-", "");
//        Long timestamp = (new Date()).getTime();
//        String bodys=aesEncrypt(body,bdpUserKey);
//        String signadd = bdpUserSecret + api + body + noncestr + timestamp + bdpUserKey;
////		String signadd = "XX5rPb7q4G9jzhMVExNyOKNBomZUpQU/jEw+wsCD1fdeIGJpxVqYs5A8hEcsKQ4XaZLpn0i0tiOF" + "+gcmxNiE44hJmr2V2q2MfTAaYl2TOme7QCVcKk00pJw/jtswZs1nVppAMGqUor8DOsbysAjmfdIh" + "sSDrcikZcZxy7oqQ/gk=";
//        String sign = aesEncrypt(signadd,bdpUserKey);
//        sign = sign.replaceAll("\r|\n", "");
//        HttpResponse res = HttpRequest.post(bdpGwUrl).
//                header("Content-Type", contentTyped)
//                .header("INTERFACECODE", api)
//                .header("DCRMCODE", bdpUserSecret)
//                .header("NONCESTR", noncestr)
//                .header("TIMESTAMP", timestamp.toString())
//                .header("SIGN", sign)
//                .timeout(5000)
//                .body(bodys)
//                .execute();
//        logger.info("status -----> " + res.getStatus());
//        logger.info("body -----> " + res.body());
//        String rest ="";
//        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
//        Boolean isLegal = res.body().matches(base64Pattern);
//        if (isLegal) {
//            rest = aesDecrypt(res.body(),bdpUserKey);
//            logger.info("输入的不是Base64编码的字符串,已转换");
//        }else {
//            rest = res.body();
//        }
//        return rest;
//    }
//}
